package com.cxhc.system.service.hcdoc.impl;

import com.cxhc.common.utils.DateUtils;
import com.cxhc.common.utils.StringUtils;
import com.cxhc.system.domain.hcdoc.HdApprovalForm;
import com.cxhc.system.domain.hcdoc.HdBranchBudget;
import com.cxhc.system.domain.hcdoc.HdParkMonthly;
import com.cxhc.system.domain.hcdoc.HdPetitionAgent;
import com.cxhc.system.domain.hcdoc.HdProjectDocInfo;
import com.cxhc.system.domain.hcdoc.HdProjectInfo;
import com.cxhc.system.domain.hcdoc.HdSmallBell;
import com.cxhc.system.domain.hcdoc.HdSmallBid;
import com.cxhc.system.domain.hcdoc.HdUserInfo;
import com.cxhc.system.domain.hcdoc.HdYearFile;
import com.cxhc.system.mapper.hcdoc.HcDocUserMapper;
import com.cxhc.system.mapper.hcdoc.HdApprovalFormMapper;
import com.cxhc.system.mapper.hcdoc.HdBranchBudgetMapper;
import com.cxhc.system.mapper.hcdoc.HdParkMonthlyMapper;
import com.cxhc.system.mapper.hcdoc.HdPetitionAgentMapper;
import com.cxhc.system.mapper.hcdoc.HdProjectDocInfoMapper;
import com.cxhc.system.mapper.hcdoc.HdProjectInfoMapper;
import com.cxhc.system.mapper.hcdoc.HdSmallBellMapper;
import com.cxhc.system.mapper.hcdoc.HdSmallBidMapper;
import com.cxhc.system.mapper.hcdoc.HdYearFileMapper;
import com.cxhc.system.service.hcdoc.HdApprovalFormService;
import com.cxhc.system.service.hcdoc.HdProjectInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;


@Service
public class HdApprovalFormServiceImpl implements HdApprovalFormService {

    @Autowired
    private HdApprovalFormMapper hdApprovalFormMapper;

    @Autowired
    private HdProjectInfoMapper hdProjectInfoMapper;

    @Autowired
    private HdBranchBudgetMapper hdBranchBudgetMapper;

    @Autowired
    private HdProjectDocInfoMapper hdProjectDocInfoMapper;

    @Autowired
    private HdPetitionAgentMapper hdPetitionAgentMapper;

    @Autowired
    private HdYearFileMapper hdYearFileMapper;

    @Autowired
    private HdParkMonthlyMapper hdParkMonthlyMapper;

    @Autowired
    private HdSmallBidMapper hdSmallBidMapper;

    @Override
    public Map<String, Object> selectById(String id) {
        Map<String, Object> map = hdApprovalFormMapper.selectDetialById(id);
        List<HdProjectDocInfo> hdProjectDocInfos = hdProjectDocInfoMapper.selectListByProjectId((String) map.get("projectInfoId"));
        map.put("projectDocs",hdProjectDocInfos);
        return map;
    }

    @Override
    public int insert(HdApprovalForm hdApprovalForm) {

        String formType = hdApprovalForm.getFormType();
        switch (formType){
            case "1":
            case "2":
                insertForProject(hdApprovalForm);
                break;
            case "3":
                insertForPetitonAgent(hdApprovalForm);
                break;
            case "4":
                insertForYearFile(hdApprovalForm);
                break;
            case "5":
                insertForParkMonthly(hdApprovalForm);
                break;
            case "6":
                insertForSmallBid(hdApprovalForm);
                break;
            default:
                throw new RuntimeException("审批类型错误！！！");

        }
        return hdApprovalFormMapper.insert(hdApprovalForm);
    }

    private void insertForPetitonAgent(HdApprovalForm hdApprovalForm) {
        String projectInfoId = hdApprovalForm.getProjectInfoId();
        List<HdApprovalForm> hdApprovalForms = hdApprovalFormMapper.selectListForPetitionAgent(projectInfoId);
        if (!CollectionUtils.isEmpty(hdApprovalForms)){
            throw new RuntimeException("该信访件存在审批中记录,请审批后重试!!!");
        }
        hdApprovalForm.setFormStat("1");
    }

    private void insertForYearFile(HdApprovalForm hdApprovalForm) {
        String projectInfoId = hdApprovalForm.getProjectInfoId();
        List<HdApprovalForm> hdApprovalForms = hdApprovalFormMapper.selectListForYearFile(projectInfoId);
        if (!CollectionUtils.isEmpty(hdApprovalForms)){
            throw new RuntimeException("该年度资料存在审批中记录,请审批后重试!!!");
        }
        hdApprovalForm.setFormStat("1");
    }

    private void insertForParkMonthly(HdApprovalForm hdApprovalForm) {
        String projectInfoId = hdApprovalForm.getProjectInfoId();
        List<HdApprovalForm> hdApprovalForms = hdApprovalFormMapper.selectListForParkMonthly(projectInfoId);
        if (!CollectionUtils.isEmpty(hdApprovalForms)){
            throw new RuntimeException("该停车包月存在审批中记录,请审批后重试!!!");
        }
        hdApprovalForm.setFormStat("1");
    }

    private void insertForSmallBid(HdApprovalForm hdApprovalForm) {
        String projectInfoId = hdApprovalForm.getProjectInfoId();
        List<HdApprovalForm> hdApprovalForms = hdApprovalFormMapper.selectListForSmallBid(projectInfoId);
        if (!CollectionUtils.isEmpty(hdApprovalForms)){
            throw new RuntimeException("该小额招标存在审批中记录,请审批后重试!!!");
        }
        hdApprovalForm.setFormStat("1");
    }

    private void insertForProject(HdApprovalForm hdApprovalForm) {
        String projectInfoId = hdApprovalForm.getProjectInfoId();
        List<HdApprovalForm> hdApprovalForms = hdApprovalFormMapper.selectListByProjectId(projectInfoId);
        if (!CollectionUtils.isEmpty(hdApprovalForms)){
            throw new RuntimeException("该项目存在审批中记录,请审批后重试!!!");
        }
        HdProjectInfo hdProjectInfo = hdProjectInfoMapper.selectById(projectInfoId);
        //如果是一次性付清 支付金额等于项目金额,分期支付金额等于合同金额除分期数
        String contractAmountStr = hdProjectInfo.getContractAmount().replaceAll(",", "");
        if ("1".equals(hdApprovalForm.getFormType())){
            if (contractAmountStr.equals(hdProjectInfo.getPaidAmount().replaceAll(",", ""))){
                throw new RuntimeException("该项目已经全部支付,不可再支付!!!");
            }
            //判断当前日期是否在 支付节点前后七天时间范围内
            String nextPayDate = hdProjectInfo.getNextPayDate();
            Date today = DateUtils.getNowDate();
            Date date = DateUtils.dateTime(DateUtils.YYYY_MM_DD, nextPayDate);
            //获取后7天时间
            Calendar calendarAfter = Calendar.getInstance();
            calendarAfter.setTime(date);
            String advanceNoticeDays = hdProjectInfo.getAdvanceNoticeDays();
            calendarAfter.add(Calendar.DAY_OF_MONTH,Integer.parseInt(advanceNoticeDays));
            Date dateAfterSevenDay = calendarAfter.getTime();
            //获取前7天时间
            Calendar calendarBefore = Calendar.getInstance();
            calendarBefore.setTime(date);
            calendarBefore.add(Calendar.DAY_OF_MONTH,Integer.parseInt("-" + advanceNoticeDays));
            Date dateBeforeSevenDay = calendarBefore.getTime();
            if (!(today.after(dateBeforeSevenDay) && today.before(dateAfterSevenDay))){
                throw new RuntimeException("当前日期不在支付节点时间区间范围内(支付节点前后" + advanceNoticeDays + "天)");
            }
            if ("1".equals(hdProjectInfo.getPayType())){
                hdApprovalForm.setPayAmount(contractAmountStr);

            }else {
                String payDates = hdProjectInfo.getPayDates();
                if (!StringUtils.isEmpty(payDates)){
                    String[] split = payDates.split(",");
                    for (int i = 0; i < split.length; i++) {
                        String s = split[i];
                        if (s.contains(nextPayDate)){
                            hdApprovalForm.setPayAmount(s.split("@")[1]);
                        }
                    }
                }
            }
        }else {
            if (!contractAmountStr.equals(hdProjectInfo.getPaidAmount().replaceAll(",", ""))){
                throw new RuntimeException("该项目未全部支付不予存档!!!");
            }
        }
    }


    @Override
    public List<HdApprovalForm> selectList(HdApprovalForm hdApprovalForm) {
        return hdApprovalFormMapper.selectList(hdApprovalForm);
    }

    @Override
    public int approval(HdApprovalForm hdApprovalForm) {
        //审批通过
        if ("2".equals(hdApprovalForm.getFormStat())){
            String formType = hdApprovalForm.getFormType();
            switch (formType){
                case "1":
                case "2":
                    approvalForProject(hdApprovalForm);
                    break;
                case "3":
                    approvalForPetitionAgent(hdApprovalForm);
                    break;
                case "4":
                    approvalForYearFile(hdApprovalForm);
                    break;
                case "5":
                    approvalForParkMonthly(hdApprovalForm);
                    break;
                case "6":
                    approvalForSmallBid(hdApprovalForm);
                    break;
                default:
                    throw new RuntimeException("审批类型错误！！！");
            }
        }
        return hdApprovalFormMapper.updateStatus(hdApprovalForm);
    }

    private void approvalForPetitionAgent(HdApprovalForm hdApprovalForm) {
        HdPetitionAgent hdPetitionAgent = hdPetitionAgentMapper.selectHdPetitionAgentByPetitionNo(hdApprovalForm.getProjectInfoId());
        hdPetitionAgent.setPigeonholeStatus(1);
        hdPetitionAgentMapper.updateHdPetitionAgent(hdPetitionAgent);
    }

    private void approvalForYearFile(HdApprovalForm hdApprovalForm) {
        HdYearFile hdYearFile = hdYearFileMapper.selectHdYearFileById(Long.parseLong(hdApprovalForm.getProjectInfoId()));
        hdYearFile.setPigeonholeStatus(1);
        hdYearFileMapper.updateHdYearFile(hdYearFile);
    }

    private void approvalForParkMonthly(HdApprovalForm hdApprovalForm) {
        HdParkMonthly hdParkMonthly = hdParkMonthlyMapper.selectHdParkMonthlyById(Long.parseLong(hdApprovalForm.getProjectInfoId()));
        hdParkMonthly.setPigeonholeStatus(1);
        hdParkMonthlyMapper.updateHdParkMonthly(hdParkMonthly);
    }

    private void approvalForSmallBid(HdApprovalForm hdApprovalForm) {
        HdSmallBid hdSmallBid = hdSmallBidMapper.selectHdSmallBidById(Long.parseLong(hdApprovalForm.getProjectInfoId()));
        hdSmallBid.setPigeonholeStatus(1);
        hdSmallBidMapper.updateHdSmallBid(hdSmallBid);
    }

    private void approvalForProject(HdApprovalForm hdApprovalForm) {
        HdApprovalForm hdApprovalFormTemp = hdApprovalFormMapper.selectById(String.valueOf(hdApprovalForm.getId()));
        HdProjectInfo hdProjectInfo = hdProjectInfoMapper.selectById(hdApprovalFormTemp.getProjectInfoId());
        HdBranchBudget hdBranchBudget = hdBranchBudgetMapper.selectByBranchInfoIdAndYear(hdProjectInfo.getBranchInfoId(), hdProjectInfo.getCtime().substring(0, 4));
        BigDecimal paidAmount = new BigDecimal(hdProjectInfo.getPaidAmount().replaceAll(",", ""));
        String contractAmountStr = hdProjectInfo.getContractAmount().replaceAll(",", "");
        BigDecimal payAmount = new BigDecimal(hdApprovalFormTemp.getPayAmount().replaceAll(",", ""));
        BigDecimal contractAmount = new BigDecimal(contractAmountStr);
        //支付合同款
        HdProjectInfo hdProjectInfoForUpate = new HdProjectInfo();
        hdProjectInfoForUpate.setId(hdProjectInfo.getId());

        if ("1".equals(hdApprovalFormTemp.getFormType())){
            HdBranchBudget hdBranchBudgetForUpdate = new HdBranchBudget();
            hdBranchBudgetForUpdate.setId(hdBranchBudget.getId());
            //一次性付清
            Date nextPayDate = DateUtils.dateTime(DateUtils.YYYY_MM_DD, hdProjectInfo.getNextPayDate());
            if ("1".equals(hdProjectInfo.getPayType())){
                hdProjectInfoForUpate.setPaidAmount(contractAmountStr);
                hdBranchBudgetForUpdate.setPaidAmount(String.valueOf(new BigDecimal(hdBranchBudget.getPaidAmount().replaceAll(",","")).add(contractAmount)));
                hdProjectInfoForUpate.setNextPayDate("9999-12-31");
                hdProjectInfoForUpate.setNowPayNode(hdProjectInfo.getNextPayDate());
            }else {
                String[] split = hdProjectInfo.getPayDates().split(",");
                List<Date> dates = new LinkedList<>();
                for (int i = 0; i < split.length; i++) {
                    dates.add(DateUtils.dateTime(DateUtils.YYYY_MM_DD, split[i].split("@")[0]));
                }
                Collections.sort(dates);
                int index = dates.indexOf(nextPayDate);

                if (index == dates.size()-1){
                    hdProjectInfoForUpate.setNextPayDate("9999-12-31");
                }else {
                    hdProjectInfoForUpate.setNextPayDate(DateUtils.dateTime(dates.get(index+1)));
                }
                hdBranchBudgetForUpdate.setPaidAmount(String.valueOf(new BigDecimal(hdBranchBudget.getPaidAmount().replaceAll(",","")).add(payAmount)));
                hdProjectInfoForUpate.setNowPayNode(DateUtils.dateTime(nextPayDate));
                hdProjectInfoForUpate.setPaidAmount(String.valueOf(paidAmount.add(payAmount)));
            }
            hdBranchBudgetMapper.update(hdBranchBudgetForUpdate);
        }else {
            //存档
            hdProjectInfoForUpate.setStat("1");
        }
        hdProjectInfoMapper.update(hdProjectInfoForUpate);

    }
}
